package alarmsdk

import (
	"fmt"

	dgctx "github.com/darwinOrg/go-common/context"
	dgsys "github.com/darwinOrg/go-common/sys"
	dgding "github.com/darwinOrg/go-dingtalk"
	dgfeishu "github.com/darwinOrg/go-feishu"
	dglogger "github.com/darwinOrg/go-logger"
)

const (
	PlatformFeishu   = "feishu"
	PlatformDingTalk = "dingtalk"
)

var (
	DefaultPlatform = PlatformFeishu

	EmergencyWebhookMap = map[string]string{
		"qa":   "https://open.feishu.cn/open-apis/bot/v2/hook/xxx1",
		"pre":  "https://open.feishu.cn/open-apis/bot/v2/hook/xxx2",
		"prod": "https://open.feishu.cn/open-apis/bot/v2/hook/xxx3",
	}

	NormalWebhookMap = map[string]string{
		"qa":   "https://open.feishu.cn/open-apis/bot/v2/hook/xxx4",
		"pre":  "https://open.feishu.cn/open-apis/bot/v2/hook/xxx5",
		"prod": "https://open.feishu.cn/open-apis/bot/v2/hook/xxx6",
	}
)

func EmergencyAlarm(ctx *dgctx.DgContext, content string) {
	WebhookAlarm(ctx, DefaultPlatform, EmergencyWebhookMap[dgsys.GetProfile()], content)
	dglogger.Error(ctx, content)
}

func NormalAlarm(ctx *dgctx.DgContext, content string) {
	WebhookAlarm(ctx, DefaultPlatform, NormalWebhookMap[dgsys.GetProfile()], content)
	dglogger.Warn(ctx, content)
}

func WebhookAlarm(ctx *dgctx.DgContext, platform, webhook, content string) {
	if webhook == "" || content == "" {
		return
	}

	if platform == "" {
		platform = DefaultPlatform
	}

	if ctx.TraceId != "" {
		content = fmt.Sprintf("%s\nTraceId：%s", content, ctx.TraceId)
	}

	var err error
	switch platform {
	case PlatformDingTalk:
		_, err = dgding.SimpleSendTextMessage(ctx, webhook, content)
	default:
		_, err = dgfeishu.SimpleSendTextMessage(ctx, webhook, content)
	}
	if err != nil {
		dglogger.Warnf(ctx, "[%s] 告警失败: %v", platform, err)
	}
}
